from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection

import json,base64,pickle
from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE
# Create your views here.


class CartsSimpleView(View):
    """简单展示购物车"""
    def get(self,request):
        """展示购物车"""
        user = request.user
        # 判断用户是否存在
        if user.is_authenticated:
            # 用户登入，从redis中获取数据
            redis_conn = get_redis_connection('carts')
            redis_dict = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)

            """
            {
                "sku_id1":{
                    "count":"1",
                    "selected":"True"
                },
                "sku_id3":{
                    "count":"3",
                    "selected":"False"
                }
            }
            """
            cart_dict = {}
            for sku_id, count in redis_dict.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            # 用户未登录，查询cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 构造简单购物车JSON数据
        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict[sku.id]['count'],
                'default_image_url': sku.default_image.url
            })

        # 响应json列表数据
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'cart_skus': cart_skus})


class CartsSelectAllView(View):
    """全选购物车"""

    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)

        # 校验参数
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')

            # 获取所有的记录 {b'3': b'1', b'5': b'2'}
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 获取字典中所有的key [b'3', b'5']
            redis_sku_ids = redis_cart.keys()
            # 判断用户是否全选
            if selected:
                # 全选
                redis_conn.sadd('selected_%s' % user.id, *redis_sku_ids)
            else:
                # 取消全选
                redis_conn.srem('selected_%s' % user.id, *redis_sku_ids)

            # 响应结果
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
        else:
            # 用户未登录，操作cookie购物车
            # 获取cookie中的购物车数据，并且判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')

            # 构造响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})

            if cart_str:
                # 将 cart_str转成bytes类型的字符串
                cart_str_bytes = cart_str.encode()
                # 将cart_str_bytes转成bytes类型的字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)
                # 将cart_dict_bytes转成真正的字典
                cart_dict = pickle.loads(cart_dict_bytes)

                # 遍历所有的购物车记录
                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected # True / False

                # 将cart_dict转成bytes类型的字典
                cart_dict_bytes = pickle.dumps(cart_dict)
                # 将cart_dict_bytes转成bytes类型的字符串
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                # 将cart_str_bytes转成字符串
                cookie_cart_str = cart_str_bytes.decode()

                # 重写将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str)

            return response


class CartsView(View):
    """购物车管理"""
    def post(self,request):
        """添加购物车"""
        # 接受参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 校验参数
        if not all([sku_id,count]):
            return http.HttpResponseForbidden('缺少必传的参数')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')

        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden('参数count错误')
        # 校验勾选是否是bool
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected错误')
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 如果用户已登录，操作Redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 新增购物车数据
            # 需要以增量计算的形式保存商品数据
            pl.hincrby("carts_%s" % user.id, sku_id, count)
            # 保存商品勾选状态
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)

            pl.execute()

            # 响应结果
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
        else:
            # 用户未登入保存到cookie中
            # 获取cookie中的购物车数据，并且判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')

            if cart_str:
                # 二进制字符串
                cart_str_byte = cart_str.encode()
                # cart_str_byte 转换成二进制的字典
                cart_dict_byte = base64.b64decode(cart_str_byte)
                # cart_dict_byte转换成真正的字典
                cart_dict = pickle.loads(cart_dict_byte)
            else:
                cart_dict = {}
                """
                {
                'sku_id1':{
                    "count":1,
                    "selected": True
                    },
                    }
                """
            # 判断当钱商品在cookie中是否存在
            if sku_id in cart_dict:
                # 购物车已存在，增量计算
                origin_count = cart_dict[sku_id]['count']
                count += origin_count

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 将cart_dict转成bytes类型的字典
            cart_dict_bytes = pickle.dumps(cart_dict)
            # 将cart_dict_bytes转成bytes类型的字符串
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            # 将cart_str_bytes转成字符串
            cookie_cart_str = cart_str_bytes.decode()

            # 构造响应对象
            response = http.JsonResponse( {'code': RETCODE.OK, 'errmsg': 'OK'} )
            # 重写将购物车数据写入到cookie
            response.set_cookie('carts', cookie_cart_str)

            return response

    def get(self,request):
        """展示购物车"""
        # 判断用户是否登入
        user = request.user
        if user.is_authenticated:
            # 用户已登入
            redis_coon = get_redis_connection('carts')
            # 查询hash数据 {b'3': b'1'}
            redis_cart = redis_coon.hgetall("carts_%s" % user.id)
            # # 查询set数据 {b'3'}
            redis_selected = redis_coon.smembers('selected_%s' % user.id)
            # 构建数据
            cart_dict = {}

            """
            {  将redis中的数据构造成跟cookie中的格式一致，方便统一查询
                "sku_id1":{
                    "count":"1",
                    "selected":"True"
                },
                "sku_id2":{
                    "count":"2",
                    "selected":"True"
                },
            }
            """
            # 从数据库中取的数据是二进制所以要转成整
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in redis_selected  # 这样就可以的得到True,存在就返回True否则False
                }
        else:
            cart_str = request.COOKIES.get('carts')
            if cart_str:

                # cart_str转成二进制cart_str_byte
                cart_str_byte = cart_str.encode()
                # cart_str_byte转成二进制字典
                cart_dict_byte = base64.b64decode(cart_str_byte)
                # cart_dict_byte 转成真正的字典
                cart_dict = pickle.loads(cart_dict_byte )

            else:
                cart_dict = {}
        # 构建响应
        # 获取字典中所有的key,(sku_id)
        sku_ids = cart_dict.keys()
        # 查出所有sku用id__in=
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str( cart_dict.get( sku.id ).get('selected')),  # 将True，转'True'，方便json解析
                'default_image_url': sku.default_image.url,
                'price': str(sku.price ),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })
        context = {
            "cart_skus":cart_skus
        }
        return render(request, 'cart.html', context)

    def put(self, request):
        """修改购物车"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品sku_id不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')

        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户已登录，修改redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            # 由于后端收到的数据是最终的结果，所以"覆盖写入"
            # redis_conn.hincrby() # 使用新值加上旧值（增量）
            pl.hset('carts_%s' % user.id, sku_id, count)
            # 修改勾选状态
            if selected:
                pl.sadd('selected_%s' % user.id, sku_id)
            else:
                pl.srem('selected_%s' % user.id, sku_id)
            # 执行
            pl.execute()

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'price': sku.price,
                'amount': sku.price * count,
                'default_image_url': sku.default_image.url
            }
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '修改购物车成功', 'cart_sku': cart_sku})
        else:
            # 用户未登入
            cart_str = request.COOKIES.get('carts')
            cart_str_bytes = cart_str.encode()
            cart_dict_bytes = base64.b64decode(cart_str_bytes)
            # 二进制字典转转成真正的字典
            cart_dict = pickle.loads(cart_dict_bytes)

            # 由于后端收到的是最终的结果，所以"覆盖写入"
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            # 创建响应对象
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'price': sku.price,
                'amount': sku.price * count,
                'default_image_url': sku.default_image.url
            }

            # 将修改后的数据保存到cookie中
            cart_dict_bytes = pickle.dumps(cart_dict)
            cart_str_bytes = base64.b64encode(cart_dict_bytes)
            cookie_cart_str = cart_str_bytes.decode()

            response = http.JsonResponse({"code": RETCODE.OK, "errmsg": 'OK','cart_sku': cart_sku})
            response.set_cookie('carts', cookie_cart_str)

            return response

    def delete(self,request):
        # 删除商品
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden('商品不存在')
        user = request.user
        # 判断用户是否登入
        if user.is_authenticated:
            redis_coon = get_redis_connection('carts')
            pl = redis_coon.pipeline()
            # 删除商品就是删除key中域名filed
            pl.hdel('carts_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)
            pl.execute()

            return http.JsonResponse( {'code': RETCODE.OK, 'errmsg': 'OK'} )
        else:
            # 用户未登录，删除cookie购物车
            # 获取cookie中的购物车数据，并且判断是否有购物车数据
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                cart_str_bytes = cart_str.encode()
                # 将cart_str_bytes转成bytes类型的字典
                cart_dict_bytes = base64.b64decode(cart_str_bytes)

                cart_dict = pickle.loads(cart_dict_bytes)
            else:
                cart_dict = {}

            # 构造响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
            if sku_id in cart_dict:
                del cart_dict[sku_id]

                cart_dict_bytes = pickle.dumps(cart_dict)
                # 将cart_dict_bytes转成bytes类型的字符串
                cart_str_bytes = base64.b64encode(cart_dict_bytes)
                # 将cart_str_bytes转成字符串
                cookie_cart_str = cart_str_bytes.decode()

                # 写入新的cookie
                response.set_cookie( 'carts', cookie_cart_str )

            return response